package com.websocket.config.socketJSAndStomp;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @作者: 林江
 * @创建时间: 2023/12/18
 * @功能: 基于STOMP实现的websocket配置
 */
@Configuration
@EnableWebSocketMessageBroker // 开启消息websocket代理
public class MyWebSocketJSConfig implements WebSocketMessageBrokerConfigurer {

    /**
     * 注册STOMP webscoket的端点,实现握手
     *
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/test");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 启用一个简单的消息代理
        registry.enableSimpleBroker("/topic");
        // 启用外部消息代理
//        registry.enableStompBrokerRelay("/topic");
        registry.setApplicationDestinationPrefixes("/app");

        // 配置点（.）作为分割符号。如映射 http.hello.xxxx
//        registry.setPathMatcher(new AntPathMatcher("."));
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(channelInterceptor()); // 配置拦截器
    }

    @Bean
    public ChannelInterceptor channelInterceptor() {
        return new ChannelInterceptor() {
            /**
             * 当客户端与websocket进行握手的时候，进行权限校验
             * @param message
             * @param channel
             * @return
             */
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                System.out.println("通道连接器，做权限验证。。。。");
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                //1、判断是否首次连接
                if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())) {

                    return message;
                }
                //不是首次连接，已经登陆成功
                return message;
            }
        };
    }

}
